package com.quan.system.web.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quan.common.bean.PageBean;
import com.quan.common.bean.ResultBean;
import com.quan.common.core.MyBaseController;
import com.quan.system.common.tree.MenuTreeGridUtil;
import com.quan.system.common.tree.MenuTreeNode;
import com.quan.system.entity.SystemMenu;
import com.quan.system.service.SystemMenuService;
import com.quan.system.service.SystemPermissionService;

/**
 * <p>
 * 通用用户权限系统-菜单表 前端控制器
 * </p>
 *
 * @author 杨浩泉
 * @since 2019-06-03
 */
@RestController
@RequestMapping("/system/menu")
public class SystemMenuController extends MyBaseController {
	
	@Autowired
	private SystemMenuService service;

	@Autowired
	private SystemPermissionService permissionService;

	/**
	 * 添加
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/add")
	public Object add(@Valid @RequestBody SystemMenu entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultBean.warning(bindingResult.getFieldError().getRejectedValue().toString());
		}
		boolean save = this.service.save(entity);
		if (save) {
			return ResultBean.ok("提交成功");
		} else {
			return ResultBean.failure("提交失败");
		}
	}

	/**
	 * 根据ID删除
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/deleteById/{id}")
	public Object deleteById(@PathVariable String id) {
		if (StringUtils.isNotBlank(id)) {
			boolean remove = this.service.removeById(id);
			if (remove) {
				return ResultBean.ok();
			} else {
				return ResultBean.failure("通过ID删除失败：[ " + id + " ]");
			}
		}
		return ResultBean.failure("请选项需要删除的记录");
	}

	/**
	 * 批量删除
	 * 
	 * @param params idList:["1","2"]
	 * @return
	 */
	@PostMapping("/deleteBatchIds")
	public Object deleteBatchIds(@RequestBody Map<String, Object> params) {
		System.out.println(params);
		if (null != params && !params.isEmpty()) {
			List<Long> idList = JSON.parseArray(params.get("idList").toString(), Long.class);
			boolean remove = this.service.removeByIds(idList);
			if (remove) {
				return ResultBean.ok();
			} else {
				return ResultBean.failure("通过ID删除失败：[ " + idList + " ]");
			}
		}
		return ResultBean.failure("请选项需要删除的记录");
	}

	/**
	 * 修改
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/update")
	public Object update(@Valid @RequestBody SystemMenu entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultBean.failure(bindingResult.getFieldError().getDefaultMessage().toString());
		}
		boolean update = this.service.updateById(entity);
		if (update) {
			return ResultBean.ok("修改成功");
		} else {
			return ResultBean.failure("修改失败");
		}
	}
	
	/**
	 * 根据ID查询
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/get/{id}")
	public Object get(@PathVariable Long id) {
		SystemMenu entity = this.service.getById(id);
		if (null != entity) {
			return ResultBean.ok(entity);
		} else {
			return ResultBean.failure("通过ID查询失败：[ " + id + " ]");
		}
	}

	/**
	 * 查询所有数据，不分页
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/list")
	public Object list(SystemMenu entity) {
		return ResultBean.ok(this.service.list(new QueryWrapper<SystemMenu>(entity)));
	}

	/**
	 * 分页查询数据
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/page")
	public Object page(SystemMenu entity) {
		return ResultBean.ok(this.service.selectPage(entity, new PageBean(request)));
	}
	
	/**
	 * 树状JSON结构
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/treeGrid")
	public Object treeGrid(SystemMenu entity) {
		
		QueryWrapper<SystemMenu> queryWrapper = new QueryWrapper<SystemMenu>();
		queryWrapper.orderByDesc("sort");
		List<SystemMenu> menus = this.service.list(queryWrapper) ;
		
		List<MenuTreeNode> treeNodes = new ArrayList<>();
		for (SystemMenu menu : menus) {
			MenuTreeNode node = new MenuTreeNode();
			node.setId(menu.getId());
			node.setPid(menu.getPid());
			node.setName(menu.getName());
			node.setUrl(menu.getUrl());
			node.setSort(menu.getSort());
			node.setStatus(menu.getStatus());
			node.setMethod(menu.getMethod());
			node.setIcon(menu.getIcon());
			node.setCtime(menu.getCtime());
			node.setUtime(menu.getUtime());
			
			treeNodes.add(node);
		}
		
		return ResultBean.ok(new MenuTreeGridUtil().tree(treeNodes));
	}

	/**
	 * 菜单树状结构，并查询对应的权限
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/treeGridOnPermission")
	public Object treeGridOnPermission(SystemMenu entity) {
		
		QueryWrapper<SystemMenu> queryWrapper = new QueryWrapper<SystemMenu>();
		queryWrapper.orderByDesc("sort");
		List<SystemMenu> menus = this.service.list(queryWrapper) ;
		
		List<MenuTreeNode> treeNodes = new ArrayList<>();
		for (SystemMenu menu : menus) {
			MenuTreeNode node = new MenuTreeNode();
			node.setId(menu.getId());
			node.setPid(menu.getPid());
			node.setName(menu.getName());
			node.setUrl(menu.getUrl());
			node.setStatus(menu.getStatus());
			
			//获取菜单对于的权限
			node.setPermission(this.permissionService.findPermissionByMenuId(menu.getId()));
			
			treeNodes.add(node);
		}
		
		return ResultBean.ok(new MenuTreeGridUtil().tree(treeNodes));
	}
	
}
